package com.client.Filter;

import com.alibaba.fastjson.JSON;
import com.client.pojo.Users;
import com.client.utils.JwtUtils;
import com.client.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

@WebFilter("/*")
@Component
public class LoginFilter implements Filter {
    @Autowired
    RedisUtils redisUtils;
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String path = httpRequest.getRequestURI();
        if (path.contains("/users")||path.contains("/sendCode")||path.contains("/verify")) {
            chain.doFilter(request, response);
            return;
        }
        //验证token
        String jwtToken = httpRequest.getHeader("token");
        System.out.println("jwtToken:" + jwtToken);
        //验证jwt
        try {
            Claims claims = JwtUtils.parseJWT(jwtToken);
            System.out.println("当前登录的用户信息:" + claims.getSubject());
            Users u = JSON.parseObject(claims.getSubject(), Users.class);
            System.out.println("u:" + u);
            if (!redisUtils.hasKey("token"+u.getPhone())){
                throw new Exception("服务端token错误");
            }
        }catch (Exception e){ //1:格式错误，2:过期
            System.out.println("jwt错误:" + e.getMessage());
            httpResponse.sendRedirect("/login");
            return ;
        }
        chain.doFilter(request,response);
    }
}
